﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RunAs
{
    internal class ProcessUserLogonHelper
    {
        /// <summary>
        /// 在Main函数中调用该方法的的示例代码
        /// </summary>
        private static void InvokeExample()
        {
            Process pro = ProcessUserLogonHelper.CreateProcessWithUserToken(@"C:\Program Files\Internet Explorer\iexplore.exe", "bestreme.com", "chdwu", "************");
            pro.Start();
        }

        /// <summary>
        /// 使用指定帐户绑定进程
        /// </summary>
        /// <param name="appPath">进程的宿主程序</param>
        /// <param name="domain">指定帐户的域名</param>
        /// <param name="userName">指定帐户的用户名</param>
        /// <param name="password">指定帐户的密码</param>
        /// <returns>绑定了特定帐户的进程</returns>
        public static Process CreateProcessWithUserToken(string appPath, string domain, string userName, string password)
        {
            Process pro = new Process();
            ProcessStartInfo processInfo = new ProcessStartInfo(appPath);
            processInfo.UseShellExecute = false;
            processInfo.UserName = userName;
            processInfo.Domain = domain;
            System.Security.SecureString psw = new System.Security.SecureString();
            foreach (char c in password.ToCharArray())
            {
                psw.AppendChar(c);
            }
            processInfo.Password = psw;
            processInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(appPath);
            pro.StartInfo = processInfo;
            return pro;
        }

        /// <summary>
        /// 使用指定帐户绑定进程
        /// </summary>
        /// <param name="appPath">进程的宿主程序</param>
        /// <param name="userName">指定本地帐户的用户名</param>
        /// <param name="password">指定帐户的密码</param>
        /// <returns>绑定了特定帐户的进程</returns>
        public static Process CreateProcessWithUserToken(string appPath, string userName, string password)
        {
            return CreateProcessWithUserToken(appPath, "", userName, password);
        }
    }
}
